package com.hwadee.backend.controller;

import com.hwadee.backend.entity.Apply;
import com.hwadee.backend.entity.Result;
import com.hwadee.backend.service.ApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ApplyController {
    private final ApplyService applyService;

    @Autowired
    public ApplyController(ApplyService applyService) {
        this.applyService = applyService;
    }

    
    @PostMapping("/authorize/request")
    public Result submitApply(@RequestBody AuthRequest request) {
        int applicant = request.getApplicant();
        int response = request.getResponse();
        System.out.println("Received applicant: " + applicant + ", response: " + response);

        if (applicant <= 0 || response <= 0) {
            return Result.error("参数错误：applicant和response必须为正整数");
        }
        int result = applyService.createApply(applicant, response);
        if (result > 0) {
            return Result.success("授权请求已发送成功");
        } else if (result == -1) {
            return Result.error("已存在待处理的申请");
        } else {
            return Result.error("授权请求提交失败");
        }
    }

    // 添加内部静态DTO类
    private static class AuthRequest {
        private int applicant;
        private int response;

        // Getters
        public int getApplicant() { return applicant; }
        public int getResponse() { return response; }

        // Setters
        public void setApplicant(int applicant) { this.applicant = applicant; }
        public void setResponse(int response) { this.response = response; }
    }

    // 查询授权状态 - 匹配前端/api/patients/{targetUserId}/authorization-status路径
    @GetMapping("/patients/{targetUserId}/authorization-status")
    public Result getAuthorizationStatus(
            @PathVariable int targetUserId,
            @RequestParam int applicant) {
        Apply apply = applyService.getApplyByApplicantAndTarget(applicant, targetUserId);
        Map<String, Object> data = new HashMap<>();
        if (apply != null) {
            data.put("authorized", "approved".equals(apply.getStatus()));
            data.put("status", apply.getStatus());
        } else {
            data.put("authorized", false);
            data.put("status", "not_found");
        }
        return Result.success(data);
    }

    // 用户处理申请（同意/拒绝）
    @PostMapping("/handle-apply")
    public Result handleApply(
            @RequestParam int applyId,
            @RequestParam String status) {
        if (!"approved".equals(status) && !"rejected".equals(status)) {
            return Result.error("状态必须为approved或rejected");
        }
        int rows = applyService.handleApply(applyId, status);
        if (rows > 0) {
            return Result.success("申请处理成功");
        } else {
            return Result.error("申请不存在或已处理");
        }
    }

    // 根据申请人ID查询申请列表
    @GetMapping("/applies/applicant/{applicantId}")
    public Result getAppliesByApplicant(@PathVariable int applicantId) {
        List<Apply> applies = applyService.getAppliesByApplicant(applicantId);
        return Result.success(applies);
    }

    @GetMapping("/applies/target/{targetUserId}")
    public Result getAppliesByTargetUser(@PathVariable int targetUserId) {
        List<Apply> applies = applyService.getAppliesByTargetUser(targetUserId);
        return Result.success(applies);
    }


}